import { PDFDocument } from 'pdf-lib';

// 将PDF文件拆分成单页的PDF对象
export async function splitPDFToSinglePagesAsFiles(pdfFile) {
    const fileReader = new FileReader();
    return new Promise((resolve, reject) => {
        fileReader.onload = async () => {
            try {
                const pdfBytes = new Uint8Array(fileReader.result);
                const pdfDoc = await PDFDocument.load(pdfBytes);
                const singlePageFiles = [];

                for (let i = 0; i < pdfDoc.getPageCount(); i++) {
                    const newPdfDoc = await PDFDocument.create();
                    const [copiedPage] = await newPdfDoc.copyPages(pdfDoc, [i]);
                    newPdfDoc.addPage(copiedPage);
                    const singlePageBytes = await newPdfDoc.save();
                    const singlePageBlob = new Blob([singlePageBytes], { type: 'application/pdf' });
                    const singlePageFile = new File([singlePageBlob], `page_${i + 1}.pdf`);
                    singlePageFiles.push(singlePageFile);
                }

                resolve(singlePageFiles);
            } catch (error) {
                reject(error);
            }
        };

        fileReader.onerror = error => {
            reject(error);
        };

        fileReader.readAsArrayBuffer(pdfFile);
    });
}
